'use strict';


const nunjucks = require('nunjucks');


function createEnv(path, opts) {
 
    path = path || 'views'
   
    opts = opts || {}
    
    let envOptions = {
       
        autoescape: opts.autoescape === undefined ? true : opts.autoescape,
     
        watch: opts.watch === undefined ? false : opts.watch,
       
        noCache: opts.noCache === undefined ? false : opts.noCache,
       
        throwOnUndefined: opts.throwOnUndefined === undefined ? false : opts.throwOnundefined,
      
        trimBlocks: opts.trimBlocks === undefined ? false : opts.trimBlocks,
      
        lstripBlocks: opts.lstripBlocks === undefined ? false : opts.lstripBlocks
    }
  
    let env = nunjucks.configure(path, envOptions);
    
    return env;
}


module.exports = async (ctx, next) => {
    
    ctx.render = function (view, model) {
       
        let env = createEnv('views', { watch: true, noCache: true });
        
        ctx.response.body = env.render(view, model);
    }
  
    await next();
}